package process;

import models.Animal;
import utils.Pair;

import java.util.HashMap;
import java.util.stream.Collectors;

/**
 * 字面量动物计数器
 *
 * @author huangy
 * @since 2022/8/16 11:00 下午
 */
public class ClassAnimalCounter {

    static class Counter extends HashMap<Class<? extends Animal>, Integer> {

        Counter() {
            //初始化计数器为 类型 -> 类型数量
            super(ClassAnimalCreator.ALL_TYPES.stream().map(type -> Pair.make(type, 0))
                    .collect(Collectors.toMap(Pair::key, Pair::value)));
        }

        /**
         * 计数
         *
         * @param animal 动物类
         * @author huangy
         * @since 2022/8/17 10:40 上午
         **/
        public void count(Animal animal) {
            entrySet().stream().filter(pair -> pair.getKey().isInstance(animal))
                    .forEach(pair -> put(pair.getKey(), pair.getValue() + 1));
        }

        @Override
        public String toString() {
            String result = entrySet().stream().map(pair ->
                    String.format("%s=%s", pair.getKey().getSimpleName(), pair.getValue()))
                    .collect(Collectors.joining(", "));
            return "{" + result + "}";
        }

    }

    public static void main(String[] args) {
        Counter counter = new Counter();
        new ClassAnimalCreator().stream().limit(30).peek(counter::count).forEach(p ->
                System.out.println(p.getClass().getSimpleName() + " "));
        System.out.println("\n" + counter);
    }

}
